<template>
	<n-popover
		ref="popoverRef"
		trigger="hover"
		placement="bottom-end"
		style="padding: 0"
		:show-arrow="false">
		<template #trigger>
			<div class="h-full flex items-center hover:text-primary cursor-pointer mr-3">
				<base-icon name="language" class="text-xl"></base-icon>
			</div>
		</template>
		<div class="p-4 bg-bg-8 flex leading-[24px] rounded-sm">
			<div class="flex flex-col">
				<div class="text-t-2">{{ $t('app.region') }}</div>
				<div>
					<div
						v-for="item in regionList"
						:key="item.id"
						class="app-font-bold mt-[10px] cursor-pointer hover:text-primary"
						:class="{
							'text-primary': appStore.region === item.id
						}"
						@click="onRegionSelect(item.id)">
						{{ item.text }}
					</div>
				</div>
			</div>
			<div class="ml-10 flex flex-col">
				<div class="text-t-2">{{ $t('app.language') }}</div>
				<div>
					<div
						v-for="item in langList"
						:key="item.id"
						class="app-font-bold mt-[10px] cursor-pointer hover:text-primary"
						:class="{
							'text-primary': appStore.lang === item.id
						}"
						@click="onLangSelect(item.id)">
						{{ item.text }}
					</div>
				</div>
			</div>
		</div>
	</n-popover>
</template>

<script lang="ts" setup>
import { NPopover } from 'naive-ui'
import { BaseIcon } from '@/components/base'
import { computed, ref } from 'vue'
import { getRegionList, getLangList } from '@/utils'
import { useAppStore } from '@/store'
import { Region, Lang } from '@/enums'
import { PopoverInst } from 'naive-ui'

defineOptions({ name: 'AppRegionLang' })

const popoverRef = ref<PopoverInst | null>(null)

const appStore = useAppStore()

const regionList = computed(() =>
	getRegionList().sort((_, b) => {
		if (appStore.region === b.id) {
			return 1
		} else {
			return -1
		}
	})
)

const onRegionSelect = (val: Region) => {
	appStore.setRegion(val)
	popoverRef.value?.setShow(false)
}

const onLangSelect = (val: Lang) => {
	appStore.setLang(val)
	popoverRef.value?.setShow(false)
}

const langList = computed(() =>
	getLangList().sort((_, b) => {
		if (appStore.lang === b.id) {
			return 1
		} else {
			return -1
		}
	})
)
</script>
